<!-- 字典管理 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<!-- <el-form :model="queryParams" :inline="true" :label-width="100">
			<el-form-item label="字典名称" prop="description">
				<el-input v-model="queryParams.description" placeholder="请输入字典名称" clearable class="yd-input" />
			</el-form-item>
			<el-form-item label="字典类型" prop="dictType">
				<el-input v-model="queryParams.dictType" placeholder="请输入字典类型" clearable class="yd-input" />
			</el-form-item>
			<el-form-item label="日期范围">
				<yd-date-range :config="{ enableCrossDay: true, clearBtn: true }" @pickChange="handlePickChange"></yd-date-range>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handleQuery">查 询</el-button>
			</el-form-item>
		</el-form> -->
		<yd-form ref="myForm" :options="formOptions" :model="queryParams" @change="handlerSelectChange">
			<template #form-btn>
				<div>
					<el-button class="yd-form-btn" type="primary" @click="getList">查询</el-button>
				</div>
			</template>
		</yd-form>
		<!--查询列表-->
		<YdTable
			ref="multipleTable"
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="getList"
			@currentChangeHandler="getList"
			@sortChangeHandler="getList"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>
		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="open" width="500px" append-to-body center :close-on-click-modal="false">
			<el-form ref="dictForm" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="字典名称" prop="description">
					<el-input v-model="form.description" placeholder="请输入字典名称" maxlength="30" />
				</el-form-item>
				<el-form-item label="字典类型" prop="dictType">
					<el-input v-model="form.dictType" placeholder="请输入字典类型" maxlength="50" />
				</el-form-item>
				<el-form-item label="备注" prop="remarks">
					<el-input v-model="form.remarks" maxlength="200" type="textarea" placeholder="请输入内容"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
		<DictItem ref="dictItemRef" />
	</div>
</template>

<script setup name="Dict" lang="tsx">
import { listType, getType, delType, addType, updateType, clearCache } from '@/api/admin/dict/index';
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import DictItem from './dictItem.vue';

const { proxy }: any = getCurrentInstance();
const router = useRouter();

// 选中数组
const ids = ref([]);
//选中字典名称
const dictNames = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);
// 查询参数
let queryParams = reactive<any>({
	pageNum: 1,
	pageSize: 10,
	description: null,
	dictType: null,
	dateRange: [],
});
const formOptions = reactive<FormOptionType>([
	{
		type: 'input',
		prop: 'description',
		label: '字典名称',
		attrs: {
			clearable: true,
		},
		placeholder: '请输入字典名称',
	},
	{
		type: 'input',
		prop: 'dictType',
		label: '字典类型',
		attrs: {
			clearable: true,
		},
		placeholder: '请输入字典类型',
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		dateType: 'datetimerange',
		enableCrossDay: true,
		span: 10,
		// shortcutsKeys: ['last1h', 'today', 'lastDay'],
		// defaulShortcutsKey: 'lastlh',
		defaulShortcutsKey: 'today',
		attrs: {
			clearable: true,
		},
	},
]);
// 列表配置
let tableConfig = reactive({
	columns: [
		{
			label: '字典名称',
			prop: 'description',
		},
		{
			label: '字典类型',
			prop: 'dictType',
			// render: (row: any, val: any) => {
			// 	// if (proxy.checkRole(['admin']) || proxy.checkPermi(['system:data:list'])) {
			// 	return (
			// 		// <router-link to={'/admin/systemManage/dict/data/' + row.id} class="link-type">
			// 		// 	<span>{val}</span>
			// 		// </router-link>
			// 		<el-button type="primary" link onClick={dictTypeClick.bind(this, row)}>
			// 			{val}
			// 		</el-button>
			// 	);
			// 	// }
			// 	// return <span>{val}</span>;
			// },
		},
		{
			label: '备注',
			prop: 'remarks',
			showOverFlowToolTip: true,
		},
		{
			label: '创建时间',
			prop: 'createTime',
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '修改',
					handler: (scope: any) => handleUpdate(scope.row),
					permi: ['system:dict:edit'],
				},
				{
					text: '删除',
					handler: (scope: any) => handleDelete(scope.row),
					permi: ['system:dict:remove'],
				},
				{
					text: '字典项',
					handler: (scope: any) => handleDict(scope.row),
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['system:dict:add'], handler: () => handleAdd() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['system:dict:edit'], disable: 'single', handler: () => handleUpdate() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['system:dict:remove'], disable: 'multiple', handler: () => handleDelete() },
		{
			name: '清理缓存',
			icon: 'yd-icon-refresh',
			permi: ['system:dict:cleanCache'],
			disable: 'multiple',
			handler: () => handleClearCache(),
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
// 表单参数
const data = reactive({
	form: {},
});
const { form }: any = toRefs(data);
// 表单校验
const rules = ref({
	description: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
	dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
});

function handlerSelectChange(options: BaseOptionType, value: any) {
	if (options.type === 'date-picker') {
		queryParams.startTime = value[0];
		queryParams.endTime = value[1];
	}
}
// function dictTypeClick(row: any) {
// 	router.push({
// 		path: '/admin/dict/data',
// 		query: {
// 			dictType: row.dictType,
// 		},
// 	});
// }
const dictItemRef = ref();
function handleDict(row: any) {
	dictItemRef.value.showDialog(row);
}

/** 查询字典类型列表 */
function getList() {
	tableConfig.loading = true;
	queryParams.current = queryParams.pageNum;
	queryParams.size = queryParams.pageSize;
	listType(queryParams)
		.then((response: ApiResponse) => {
			tableData.data = response.data.records;
			tableConfig.pagination.total = response.data.total;
			tableConfig.loading = false;
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}
// 表单重置
function reset() {
	form.value = {
		id: null,
		dictId: null,
		description: null,
		dictType: null,
		status: '0',
		remarks: null,
	};
}
/** 搜索按钮操作 */
function handleQuery() {
	queryParams.pageNum = 1;
	getList();
}
/** 新增按钮操作 */
function handleAdd() {
	reset();
	open.value = true;
	title.value = '添加字典类型';
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	dictNames.value = selection.map((item: any) => item.description);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
/** 修改按钮操作 */
function handleUpdate(row?: any) {
	reset();
	const dictId = row?.id || ids.value;
	getType(dictId).then((response: ApiResponse) => {
		form.value = response.data;
		open.value = true;
		title.value = '修改字典类型';
	});
}
/** 提交按钮 */
function submitForm() {
	proxy.$refs['dictForm'].validate((valid: boolean) => {
		if (valid) {
			if (form.value.id != undefined) {
				updateType(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('修改成功');
						open.value = false;
						getList();
					}
				});
			} else {
				addType(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('新增成功');
						open.value = false;
						getList();
					} else {
						proxy.$modal.msgWarning(response.msg);
					}
				});
			}
		}
	});
}
/** 删除按钮操作 */
function handleDelete(row?: any) {
	let dictIds = row?.id || ids.value;
	if (row) {
		dictNames.value = row.description;
	}
	proxy.$modal
		.confirm('是否确认删除字典名称为"' + dictNames.value + '"的数据项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			closeOnClickModal: false,
		})
		.then(function () {
			delType(dictIds).then((res: ApiResponse) => {
				if (res.code !== 0) {
					proxy.$modal.msgWarning(res.msg);
					return;
				}
				// 删除后的总条数
				let totalCount = tableData.total - ids.value.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / queryParams.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				queryParams.pageNum = queryParams.pageNum > totalPage ? totalPage : queryParams.pageNum;
				getList();
				proxy.$modal.msgSuccess('删除成功');
			});
		});
}
/** 清理缓存按钮操作 */
function handleClearCache() {
	clearCache().then((response: ApiResponse | any) => {
		if (response.code === 0) {
			proxy.$modal.msgSuccess('清理成功');
		}
	});
}
getList();
</script>
